package com.remotephone.myapplication

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.PixelFormat
import android.os.Build
import android.os.IBinder
import android.util.DisplayMetrics
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import androidx.core.app.NotificationCompat

class OverlayService : Service() {
    
    private var windowManager: WindowManager? = null
    private var overlayView: View? = null
    private var isOverlayShowing = false
    
    // 不同的浮窗模式
    private var overlayMode = OVERLAY_MODE_STANDARD
    
    companion object {
        const val ACTION_SHOW_OVERLAY = "SHOW_OVERLAY"
        const val ACTION_HIDE_OVERLAY = "HIDE_OVERLAY"
        const val ACTION_TOGGLE_OVERLAY = "TOGGLE_OVERLAY"
        const val ACTION_SET_MODE_STANDARD = "SET_MODE_STANDARD"
        const val ACTION_SET_MODE_INVISIBLE_TO_SCREENSHOT = "SET_MODE_INVISIBLE_TO_SCREENSHOT"
        const val ACTION_SET_MODE_SYSTEM_LAYER = "SET_MODE_SYSTEM_LAYER"
        const val ACTION_SET_MODE_SECURE = "SET_MODE_SECURE"
        const val ACTION_SET_OVERLAY_MODE = "SET_OVERLAY_MODE"
        const val EXTRA_OVERLAY_MODE = "overlay_mode"
        
        private const val NOTIFICATION_ID = 1
        private const val CHANNEL_ID = "OverlayServiceChannel"
        
        // 浮窗模式常量
        private const val OVERLAY_MODE_STANDARD = 0
        private const val OVERLAY_MODE_INVISIBLE_TO_SCREENSHOT = 1
        private const val OVERLAY_MODE_SYSTEM_LAYER = 2
        private const val OVERLAY_MODE_SECURE = 3
        private const val OVERLAY_MODE_SURFACE_EXCLUDED = 4  // 新增Surface排除模式
    }
    
    override fun onCreate() {
        super.onCreate()
        windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        createNotificationChannel()
    }
    
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startForeground(NOTIFICATION_ID, createNotification())
        
        when (intent?.action) {
            ACTION_SHOW_OVERLAY -> showOverlay()
            ACTION_HIDE_OVERLAY -> hideOverlay()
            ACTION_TOGGLE_OVERLAY -> toggleOverlay()
            ACTION_SET_MODE_STANDARD -> {
                overlayMode = OVERLAY_MODE_STANDARD
                if (isOverlayShowing) refreshOverlay()
            }
            ACTION_SET_MODE_INVISIBLE_TO_SCREENSHOT -> {
                overlayMode = OVERLAY_MODE_INVISIBLE_TO_SCREENSHOT
                if (isOverlayShowing) refreshOverlay()
            }
            ACTION_SET_MODE_SYSTEM_LAYER -> {
                overlayMode = OVERLAY_MODE_SYSTEM_LAYER
                if (isOverlayShowing) refreshOverlay()
            }
            ACTION_SET_MODE_SECURE -> {
                overlayMode = OVERLAY_MODE_SECURE
                if (isOverlayShowing) refreshOverlay()
            }
            ACTION_SET_OVERLAY_MODE -> {
                overlayMode = intent.getIntExtra(EXTRA_OVERLAY_MODE, OVERLAY_MODE_STANDARD)
                if (isOverlayShowing) refreshOverlay()
                Log.d("OverlayService", "切换到模式: $overlayMode")
            }
        }
        
        return START_STICKY
    }
    
    override fun onBind(intent: Intent?): IBinder? = null
    
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "屏幕遮盖服务",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "管理屏幕遮盖层的服务"
            }
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }
    
    private fun createNotification(): Notification {
        val modeText = when (overlayMode) {
            OVERLAY_MODE_STANDARD -> "标准模式"
            OVERLAY_MODE_INVISIBLE_TO_SCREENSHOT -> "截图隐形模式"
            OVERLAY_MODE_SYSTEM_LAYER -> "系统层级模式"
            OVERLAY_MODE_SECURE -> "安全模式"
            OVERLAY_MODE_SURFACE_EXCLUDED -> "Surface排除模式"
            else -> "未知模式"
        }
        
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("屏幕遮盖服务运行中")
            .setContentText("当前模式: $modeText")
            .setSmallIcon(android.R.drawable.ic_menu_camera)
            .setOngoing(true)
            .build()
    }
    
    private fun refreshOverlay() {
        hideOverlay()
        showOverlay()
    }
    
    private fun showOverlay() {
        if (isOverlayShowing || overlayView != null) return
        
        try {
            // 获取屏幕尺寸
            val displayMetrics = DisplayMetrics()
            windowManager?.defaultDisplay?.getMetrics(displayMetrics)
            val screenHeight = displayMetrics.heightPixels
            val screenWidth = displayMetrics.widthPixels
            
            // 创建黑色遮盖层，覆盖屏幕上半部分
            overlayView = View(this).apply {
                setBackgroundColor(Color.BLACK)
            }
            
            // 根据不同模式设置窗口参数
            val params = when (overlayMode) {
                OVERLAY_MODE_STANDARD -> createStandardParams(screenWidth, screenHeight)
                OVERLAY_MODE_INVISIBLE_TO_SCREENSHOT -> createInvisibleToScreenshotParams(screenWidth, screenHeight)
                OVERLAY_MODE_SYSTEM_LAYER -> createSystemLayerParams(screenWidth, screenHeight)
                OVERLAY_MODE_SECURE -> createSecureParams(screenWidth, screenHeight)
                OVERLAY_MODE_SURFACE_EXCLUDED -> createSurfaceExcludedParams(screenWidth, screenHeight)
                else -> createStandardParams(screenWidth, screenHeight)
            }
            
            windowManager?.addView(overlayView, params)
            isOverlayShowing = true
            
            Log.d("OverlayService", "浮窗已显示，模式: $overlayMode")
            
        } catch (e: Exception) {
            Log.e("OverlayService", "显示浮窗失败", e)
        }
    }
    
    private fun createStandardParams(screenWidth: Int, screenHeight: Int): WindowManager.LayoutParams {
        return WindowManager.LayoutParams().apply {
            width = screenWidth
            height = screenHeight / 2
            type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                WindowManager.LayoutParams.TYPE_PHONE
            }
            flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
                    WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
            format = PixelFormat.TRANSLUCENT
            gravity = Gravity.TOP or Gravity.START
            x = 0
            y = 0
        }
    }
    
    private fun createInvisibleToScreenshotParams(screenWidth: Int, screenHeight: Int): WindowManager.LayoutParams {
        return WindowManager.LayoutParams().apply {
            width = screenWidth
            height = screenHeight / 2
            type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                WindowManager.LayoutParams.TYPE_PHONE
            }
            // 尝试添加标志让截图时不可见
            flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
                    WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
                    WindowManager.LayoutParams.FLAG_SECURE  // 防截图标志
            format = PixelFormat.TRANSLUCENT
            gravity = Gravity.TOP or Gravity.START
            x = 0
            y = 0
        }
    }
    
    private fun createSystemLayerParams(screenWidth: Int, screenHeight: Int): WindowManager.LayoutParams {
        return WindowManager.LayoutParams().apply {
            width = screenWidth
            height = screenHeight / 2
            // 尝试使用更底层的窗口类型
            type = when {
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
                    // Android 8.0+ 限制了系统窗口类型的使用
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
                }
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> {
                    // Android 6.0-7.1 可以尝试系统层级
                    try {
                        WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY
                    } catch (e: Exception) {
                        WindowManager.LayoutParams.TYPE_PHONE
                    }
                }
                else -> {
                    WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY
                }
            }
            flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
                    WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
            format = PixelFormat.TRANSLUCENT
            gravity = Gravity.TOP or Gravity.START
            x = 0
            y = 0
        }
    }
    
    private fun createSecureParams(screenWidth: Int, screenHeight: Int): WindowManager.LayoutParams {
        return WindowManager.LayoutParams().apply {
            width = screenWidth
            height = screenHeight / 2
            type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                WindowManager.LayoutParams.TYPE_PHONE
            }
            // 组合多种防截图标志
            flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
                    WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
                    WindowManager.LayoutParams.FLAG_SECURE or  // 防截图
                    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED  // 硬件加速
            format = PixelFormat.TRANSLUCENT
            gravity = Gravity.TOP or Gravity.START
            x = 0
            y = 0
            
            // 尝试设置更低的层级
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                try {
                    // Android 9+ 可以设置层级
                    @Suppress("DEPRECATION")
                    windowAnimations = android.R.style.Animation_Toast
                } catch (e: Exception) {
                    Log.w("OverlayService", "无法设置窗口动画", e)
                }
            }
        }
    }
    
    private fun createSurfaceExcludedParams(screenWidth: Int, screenHeight: Int): WindowManager.LayoutParams {
        return WindowManager.LayoutParams().apply {
            width = screenWidth
            height = screenHeight / 2
            
            // 🎯 通过反射探索更多Window类型
            type = exploreWindowTypes()
            
            // 🎯 Surface排除核心技术：精确控制Surface合成
            flags = exploreAdvancedFlags()
                    
            format = PixelFormat.TRANSLUCENT
            gravity = Gravity.TOP or Gravity.START
            x = 0
            y = 0
            
            // 🎯 高级Surface控制 - 大量使用反射
            applyAdvancedSurfaceControl(this)
            
            Log.d("OverlayService", "🎯 Surface排除模式：多重反射控制已应用")
        }
    }
    
    private fun exploreWindowTypes(): Int {
        return try {
            Log.d("OverlayService", "🔍 探索隐藏窗口类型...")
            
            // 尝试通过反射获取更多窗口类型
            val windowManagerClass = WindowManager.LayoutParams::class.java
            val fields = windowManagerClass.declaredFields
            
            val hiddenTypes = mutableListOf<Pair<String, Int>>()
            
            for (field in fields) {
                if (field.name.startsWith("TYPE_") && field.type == Int::class.javaPrimitiveType) {
                    try {
                        field.isAccessible = true
                        val value = field.getInt(null)
                        hiddenTypes.add(field.name to value)
                        Log.d("OverlayService", "发现窗口类型: ${field.name} = $value")
                    } catch (e: Exception) {
                        // 忽略无法访问的字段
                    }
                }
            }
            
            // 尝试使用特殊的窗口类型
            val specialTypes = listOf(
                "TYPE_SCREENSHOT", // 可能存在的截图专用类型
                "TYPE_SURFACE_VIEW", // Surface视图类型
                "TYPE_MAGNIFICATION_OVERLAY", // 放大镜覆盖层
                "TYPE_DOCK_DIVIDER" // 分屏分割线
            )
            
            for (typeName in specialTypes) {
                val foundType = hiddenTypes.find { it.first == typeName }
                if (foundType != null) {
                    Log.d("OverlayService", "🎯 使用特殊窗口类型: ${foundType.first}")
                    return foundType.second
                }
            }
            
            // 默认使用APPLICATION_OVERLAY
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                WindowManager.LayoutParams.TYPE_PHONE
            }
        } catch (e: Exception) {
            Log.w("OverlayService", "窗口类型探索失败: ${e.message}")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                WindowManager.LayoutParams.TYPE_PHONE
            }
        }
    }
    
    private fun exploreAdvancedFlags(): Int {
        return try {
            Log.d("OverlayService", "🔍 探索高级Surface标志...")
            
            var flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                       WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
                       WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
                       WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED
            
            // 🎯 不使用FLAG_SECURE，因为它会导致全黑显示
            // flags = flags or WindowManager.LayoutParams.FLAG_SECURE
            
            // 通过反射探索隐藏标志
            val flagsClass = WindowManager.LayoutParams::class.java
            val fields = flagsClass.declaredFields
            
            val hiddenFlags = mutableListOf<Pair<String, Int>>()
            
            for (field in fields) {
                if (field.name.startsWith("FLAG_") && field.type == Int::class.javaPrimitiveType) {
                    try {
                        field.isAccessible = true
                        val value = field.getInt(null)
                        hiddenFlags.add(field.name to value)
                    } catch (e: Exception) {
                        // 忽略
                    }
                }
            }
            
            // 尝试有用的隐藏标志
            val usefulFlags = listOf(
                "FLAG_SCALED", // 缩放标志
                "FLAG_LOCAL_FOCUS_MODE", // 本地焦点模式
                "FLAG_SLIPPERY", // 滑动标志
                "FLAG_LAYOUT_ATTACHED_IN_DECOR", // 装饰器布局
                "FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS" // 系统栏背景
            )
            
            for (flagName in usefulFlags) {
                val foundFlag = hiddenFlags.find { it.first == flagName }
                if (foundFlag != null) {
                    flags = flags or foundFlag.second
                    Log.d("OverlayService", "🎯 应用隐藏标志: ${foundFlag.first}")
                }
            }
            
            Log.d("OverlayService", "最终标志组合: 0x${flags.toString(16)}")
            flags
        } catch (e: Exception) {
            Log.w("OverlayService", "高级标志探索失败: ${e.message}")
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
            WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
            WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
            WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED
        }
    }
    
    private fun applyAdvancedSurfaceControl(params: WindowManager.LayoutParams) {
        try {
            Log.d("OverlayService", "🔍 应用高级Surface控制...")
            
            // 1. 探索并设置私有标志
            exploreAndSetPrivateFlags(params)
            
            // 2. 设置Surface属性
            setSurfaceAttributes(params)
            
            // 3. 设置合成控制
            setCompositionControl(params)
            
        } catch (e: Exception) {
            Log.w("OverlayService", "高级Surface控制失败: ${e.message}")
        }
    }
    
    private fun exploreAndSetPrivateFlags(params: WindowManager.LayoutParams) {
        try {
            val privateFlagsField = WindowManager.LayoutParams::class.java.getDeclaredField("privateFlags")
            privateFlagsField.isAccessible = true
            
            var privateFlags = 0
            
            // 探索有用的私有标志
            val usefulPrivateFlags = mapOf(
                "PRIVATE_FLAG_NO_MOVE_ANIMATION" to 0x00000020,
                "PRIVATE_FLAG_COMPATIBLE_WINDOW" to 0x00000080,
                "PRIVATE_FLAG_LAYOUT_CHILD_WINDOW_IN_PARENT_FRAME" to 0x00010000,
                "PRIVATE_FLAG_FORCE_DECOR_VIEW_VISIBILITY" to 0x00020000,
                "PRIVATE_FLAG_WILL_NOT_REPLACE_ON_RELAUNCH" to 0x00000800,
                "PRIVATE_FLAG_LAYOUT_SIZE_EXTENDED_BY_CUTOUT" to 0x00001000
            )
            
            for ((flagName, flagValue) in usefulPrivateFlags) {
                // 🎯 选择性应用私有标志，避免导致全黑
                if (flagName != "PRIVATE_FLAG_NO_MOVE_ANIMATION") { // 这个可能导致全黑
                    privateFlags = privateFlags or flagValue
                    Log.d("OverlayService", "🎯 应用私有标志: $flagName")
                }
            }
            
            privateFlagsField.setInt(params, privateFlags)
            Log.d("OverlayService", "私有标志设置成功: 0x${privateFlags.toString(16)}")
            
        } catch (e: Exception) {
            Log.w("OverlayService", "私有标志设置失败: ${e.message}")
        }
    }
    
    private fun setSurfaceAttributes(params: WindowManager.LayoutParams) {
        try {
            // 尝试设置Surface级别的属性
            val fields = WindowManager.LayoutParams::class.java.declaredFields
            
            for (field in fields) {
                field.isAccessible = true
                
                when (field.name) {
                    "alpha" -> {
                        if (field.type == Float::class.javaPrimitiveType) {
                            field.setFloat(params, 1.0f) // 确保完全不透明
                            Log.d("OverlayService", "设置alpha = 1.0")
                        }
                    }
                    "dimAmount" -> {
                        if (field.type == Float::class.javaPrimitiveType) {
                            field.setFloat(params, 0.0f) // 不调暗
                            Log.d("OverlayService", "设置dimAmount = 0.0")
                        }
                    }
                    "screenBrightness" -> {
                        if (field.type == Float::class.javaPrimitiveType) {
                            field.setFloat(params, -1.0f) // 使用系统亮度
                            Log.d("OverlayService", "设置screenBrightness = -1.0")
                        }
                    }
                }
            }
        } catch (e: Exception) {
            Log.w("OverlayService", "Surface属性设置失败: ${e.message}")
        }
    }
    
    private fun setCompositionControl(params: WindowManager.LayoutParams) {
        try {
            // 尝试控制合成行为
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                
                // 设置窗口动画（可能影响合成）
                params.windowAnimations = android.R.style.Animation_InputMethod
                
                // 尝试设置窗口标题（用于调试）
                try {
                    val titleField = WindowManager.LayoutParams::class.java.getDeclaredField("accessibilityTitle")
                    titleField.isAccessible = true
                    titleField.set(params, "SurfaceExcluded")
                    Log.d("OverlayService", "设置窗口标题成功")
                } catch (e: Exception) {
                    Log.w("OverlayService", "窗口标题设置失败: ${e.message}")
                }
            }
        } catch (e: Exception) {
            Log.w("OverlayService", "合成控制设置失败: ${e.message}")
        }
    }
    
    private fun hideOverlay() {
        try {
            overlayView?.let { view ->
                windowManager?.removeView(view)
                overlayView = null
                isOverlayShowing = false
                Log.d("OverlayService", "浮窗已隐藏")
            }
        } catch (e: Exception) {
            Log.e("OverlayService", "隐藏浮窗失败", e)
        }
    }
    
    private fun toggleOverlay() {
        if (isOverlayShowing) {
            hideOverlay()
        } else {
            showOverlay()
        }
    }
    
    fun isOverlayVisible(): Boolean = isOverlayShowing
    
    fun getCurrentMode(): Int = overlayMode
    
    override fun onDestroy() {
        hideOverlay()
        super.onDestroy()
    }
} 